//加载模块
const express = require("express");
//创建web服务器
const server = express();
const cors = require("cors");
const mysql = require("mysql");
const pool = mysql.createPool({
  host: "127.0.2.1",
  port: 3306,
  password: "root",
  user: "root",
  database: "monoly",
  charset: "utf8",
  connectionLimit: 20,
});

const bodyParser = require("body-parser"); // 注意：在 Express 4.16.0+ 中，bodyParser 已被整合进 express.json() 和 express.urlencoded()
const { promises } = require("fs");

// 解析 JSON 格式的请求体
server.use(express.json());
server.use(
  cors({
    origin: function (origin, callback) {
      // 这里可以编写逻辑来决定是否允许某个来源
      // 例如，允许来自特定域名的请求
      // if (origin === "http://example.com" || !origin) {
      callback(null, true);
      // } else {
      // callback(new Error("Not allowed by CORS"));
      // }
    },
  })
);

//新增对局，生成编号
server.post("/newGame", (req, res) => {
  //新的一条对局数据
  //2-4条玩家数据
  const payload = req.body;
  let { player_num, start_money } = payload;
  let gamecontral_id = new Date().getTime();
  let values = [[gamecontral_id, player_num]];
  let sql1 = `INSERT INTO gamecontral (gamecontral_id, player_num, player_id, turn ) VALUES (?,?, 0, 1 );`;
  let sql2 = `INSERT INTO playercontral (gamecontral_id, player_id,money, politics_num ) VALUES (?,?,?,?)`;
  let sqlList = [sql1];

  for (var i = 0; i < player_num; i++) {
    values.push([gamecontral_id, i, start_money, 1]);
    sqlList.push(sql2);
  }
  // let sqlList = [sql1, sql2];
  Promise.all(
    sqlList.map((sql, index) => {
      return new Promise((resolve, reject) => {
        pool.query(sql, values[index], (error, results) => {
          if (error) {
            reject(error);
          } else {
            resolve(results);
          }
        });
      });
    })
  )
    .then((results) => {
      // console.log("All queries executed successfully:", results);
      let resdata = {
        code: 200,
        msg: "操作成功",
        data: results,
      };

      res.send(resdata);
      // connection.end();
    })
    .catch((error) => {
      console.error("Error executing queries:", error);
      // connection.end();
    });
});
//根据武将id查询单个武将详情
server.get("/queryGeneralDetail", (req, res) => {
  let sql =
    "SELECT general_id, general_name, general_pow, general_int, general_type, general_image, general_rarity, tactic_name, stratagem_name, politics_name, salary FROM general JOIN stratagem ON general.stratagem_id = stratagem.stratagem_id JOIN tactic ON general.tactic_id = tactic.tactic_id JOIN politics ON general.politics_id = politics.politics_id WHERE general.general_id =" +
    req.query.general_id;

  pool.query(sql, (error, results) => {
    if (error) throw error;
    let resdata = {
      code: 200,
      data: results,
    };
    res.send(resdata);
  });
});
//根据玩家id查询麾下武将
server.get("/queryGeneralByPlayerId", (req, res) => {
  console.log("query！", req.query, req.params, req.body);
  // let sql = "SELECT id,name,pow,sway FROM general WHERE id=" + req.query.id;
  let sql =
    "SELECT general_id, general_name, general_pow, general_int, general_type, general_image, general_rarity, tactic_name, stratagem_name, politics_name, salary FROM general JOIN stratagem ON general.stratagem_id = stratagem.stratagem_id JOIN tactic ON general.tactic_id = tactic.tactic_id JOIN politics ON general.politics_id = politics.politics_id WHERE general.player_id =" +
    req.query.player_id;

  pool.query(sql, (error, results) => {
    if (error) throw error;
    let resdata = {
      code: 200,
      data: results,
    };
    res.send(resdata);
  });
});
//获取地图数据
server.get("/getmap", (req, res) => {
  let sql =
    "SELECT land_id, land_type, land_name, land_image, land_price, land_level, business, population, build, toll, income, recruit, def, parameter, general_id_0, general_id_1  FROM land";

  pool.query(sql, (error, results) => {
    if (error) throw error;
    let resdata = {
      code: 200,
      data: results,
    };
    res.send(resdata);
  });
});
//指定web服务器监听的端口
server.listen(7788);
console.log("启动！");
